package com.irdstudio.efp.console.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.service.dao.CoeffCfgAppDao;
import com.irdstudio.efp.console.service.dao.CoeffCfgDao;
import com.irdstudio.efp.console.service.domain.CoeffCfg;
import com.irdstudio.efp.console.service.domain.CoeffCfgApp;
import com.irdstudio.efp.console.service.facade.CoeffCfgAppService;
import com.irdstudio.efp.console.service.facade.PubSysInfoService;
import com.irdstudio.efp.console.service.vo.CoeffCfgAppVO;
import com.irdstudio.efp.flow.common.vo.PageApproveVO;
import com.irdstudio.basic.framework.core.base.FrameworkService;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.util.TimeUtil;

/**
 * <p>
 * 提额系数调整申请表的Service实现类
 * </p>
 * 
 * @author szbd
 * @createDate 2018-09-17 15:10:24
 */
@Service("coeffCfgAppService")
public class CoeffCfgAppServiceImpl implements CoeffCfgAppService,
		FrameworkService {

	private static Logger logger = LoggerFactory
			.getLogger(CoeffCfgAppServiceImpl.class);

	@Autowired
	private CoeffCfgAppDao coeffCfgAppDao;

	@Autowired
	private CoeffCfgDao coeffCfgDao;
	
	@Autowired
	private PubSysInfoService pubSysInfoService;

	@Override
	public List<CoeffCfgAppVO> queryAllOwner(CoeffCfgAppVO inCoeffCfgAppVo) {
		logger.info("查询本人所属的提额系数调整申请表记录的请求参数为："
				+ JSONObject.toJSONString(inCoeffCfgAppVo));
		if (Objects.isNull(inCoeffCfgAppVo)) {
			return null;
		}
		try {
			List<CoeffCfgApp> dataList = coeffCfgAppDao.queryAllOwnerByPage(inCoeffCfgAppVo);
			if (Objects.nonNull(dataList)) {
				List<CoeffCfgAppVO> resultList = (List<CoeffCfgAppVO>) beansCopy(dataList,CoeffCfgAppVO.class);
				pageSet(resultList, inCoeffCfgAppVo);
				return resultList;
			} else {
				logger.info("查询本人所属的提额系数调整申请表记录为空！");
			}
		} catch (Exception e) {
			logger.error("查询本人所属的提额系数调整申请表记录发生异常！", e);
		}
		return null;
	}

	@Override
	public List<CoeffCfgAppVO> queryAllCurrOrg(CoeffCfgAppVO inCoeffCfgAppVo) {
		logger.info("查询本机构的提额系数调整申请表记录的请求参数为："
				+ JSONObject.toJSONString(inCoeffCfgAppVo));
		if (Objects.isNull(inCoeffCfgAppVo)) {
			return null;
		}
		try {
			List<CoeffCfgApp> dataList = coeffCfgAppDao
					.queryAllCurrOrgByPage(inCoeffCfgAppVo);
			if (Objects.nonNull(dataList)) {
				List<CoeffCfgAppVO> resultList = new ArrayList<CoeffCfgAppVO>();
				resultList = (List<CoeffCfgAppVO>) beansCopy(dataList,CoeffCfgAppVO.class);
				pageSet(resultList, inCoeffCfgAppVo);
				return resultList;
			} else {
				logger.info("查询本机构的提额系数调整申请表记录为空！");
			}
		} catch (Exception e) {
			logger.error("查询本机构的提额系数调整申请表记录发生异常！", e);
		}
		return null;
	}

	@Override
	public List<CoeffCfgAppVO> queryAllCurrDownOrg(CoeffCfgAppVO inCoeffCfgAppVo) {
		logger.info("查询本机构及下属机构的提额系数调整申请表记录的请求参数为："
				+ JSONObject.toJSONString(inCoeffCfgAppVo));
		if (Objects.isNull(inCoeffCfgAppVo)) {
			return null;
		}
		try {
			List<CoeffCfgApp> dataList = coeffCfgAppDao
					.queryAllCurrDownOrgByPage(inCoeffCfgAppVo);
			if (Objects.nonNull(dataList)) {
				List<CoeffCfgAppVO> resultList = new ArrayList<CoeffCfgAppVO>();
				resultList = (List<CoeffCfgAppVO>) beansCopy(dataList,CoeffCfgAppVO.class);
				pageSet(resultList, inCoeffCfgAppVo);
				return resultList;
			} else {
				logger.info("查询本机构及下属机构的提额系数调整申请表记录为空！");
			}
		} catch (Exception e) {
			logger.error("查询本机构及下属机构的提额系数调整申请表记录发生异常！", e);
		}
		return null;
	}

	//插入系数调整记录
	@Override
	public int insertCoeffCfgApp(CoeffCfgAppVO inCoeffCfgAppVo) {
		logger.info("新增提额系数调整申请表数据的参数为："
				+ JSONObject.toJSONString(inCoeffCfgAppVo));
		return 1;
	}
	
	//批量插入系数调整记录
	@Override
	public int insertCoeffCfgAppList(List<CoeffCfgAppVO> listIn) {
		logger.info("新增提额系数调整申请表数据的参数为："
				+ JSONObject.toJSONString(listIn));
		
		if (Objects.isNull(listIn) || listIn.size() == 0) {
			return 0;
		}
		int count = 0;
		try {
			
			count = coeffCfgAppDao.insertCoeffCfgAppList(listIn);
			
		} catch (Exception e) {
			logger.error("新增提额系数调整申请表数据发生异常！", e);
			count = -1;
		}
		logger.info("新增的提额系数调整申请表数据条数为：" + count);
		return count;
	}
	
	
	
	//校验非省级机构调整的系数是否大于省级配置
	@Override
	public int checkCoeffCfgApp(CoeffCfgAppVO inCoeffCfgAppVo) {
		logger.info("新增提额系数调整申请表数据的参数为："
				+ JSONObject.toJSONString(inCoeffCfgAppVo));
		if (Objects.isNull(inCoeffCfgAppVo)) {
			return 0;
		}
		int count = 0;
		try {
			
			String loginUserLeageOrgCode = inCoeffCfgAppVo.getLegalOrgCode();
			String typeId = inCoeffCfgAppVo.getTypeId();
			
			//设置省级查询条件
			CoeffCfg coeffCfg = new CoeffCfg();
			coeffCfg.setLegalOrgCode("00001");
			coeffCfg.setTypeId(typeId);
//			
//			CoeffCfgApp coeffCfgApp = new CoeffCfgApp();
//			beanCopy(inCoeffCfgAppVo, coeffCfgApp);
//			
//			
				CoeffCfg out = coeffCfgDao.queryCoeffCfgByLeageOrgCode(coeffCfg);
				logger.info("省级提额系数查询结果："+ JSONObject.toJSONString(out));
				
				if (out != null) {
					logger.info("新增提额系数调整申请表数据的参数为："+out);
					Double  coefficientT = Double.parseDouble(out.getCoefficient().toString());
					Double   coefficient = Double.parseDouble(inCoeffCfgAppVo.getNewCoefficient().toString());
					logger.info("新增提额系数调整申请表数据的参数为：coefficientT==" + coefficientT+",coefficient=="+coefficient);
					if (coefficient > coefficientT) {
						
						return count = -2;
//					}else {
//						logger.info("新增提额系数开始："+ JSONObject.toJSONString(inCoeffCfgAppVo));
////						count = coeffCfgAppDao.insertCoeffCfgApp(coeffCfgApp);
//						logger.info("新增提额系数结束："+ JSONObject.toJSONString(inCoeffCfgAppVo));
					}
			}
			
		} catch (Exception e) {
			logger.error("新增提额系数调整申请表数据发生异常！", e);
			count = -1;
		}
		logger.info("当前新增提额系数调整申请表数据条数为：" + count);
		return count;
	}
	
	
	

	@Override
	public int deleteCoeffCfgAppByPk(CoeffCfgAppVO inCoeffCfgAppVo) {
		logger.info("删除提额系数调整申请表数据的参数为："
				+ JSONObject.toJSONString(inCoeffCfgAppVo));
		if (Objects.isNull(inCoeffCfgAppVo)) {
			return 0;
		}
		int count = 0;
		try {
			CoeffCfgApp coeffCfgApp = new CoeffCfgApp();
			beanCopy(inCoeffCfgAppVo, coeffCfgApp);
			count = coeffCfgAppDao.deleteCoeffCfgAppByPk(coeffCfgApp);
		} catch (Exception e) {
			logger.error("删除提额系数调整申请表数据发生异常！", e);
			count = -1;
		}
		logger.info("删除的提额系数调整申请表数据条数为：" + count);
		return count;
	}

	@Override
	public int updateCoeffCfgAppByPk(CoeffCfgAppVO inCoeffCfgAppVo) {
		logger.info("修改提额系数调整申请表数据的参数为："
				+ JSONObject.toJSONString(inCoeffCfgAppVo));
		if (Objects.isNull(inCoeffCfgAppVo)) {
			return 0;
		}
		int count = 0;
		try {
			CoeffCfgApp coeffCfgApp = new CoeffCfgApp();
			beanCopy(inCoeffCfgAppVo, coeffCfgApp);
			count = coeffCfgAppDao.updateCoeffCfgAppByPk(coeffCfgApp);
		} catch (Exception e) {
			logger.error("修改数据发生异常！", e);
			count = -1;
		}
		logger.info("修改的提额系数调整申请表数据条数为" + count);
		return count;
	}

	@Override
	public CoeffCfgAppVO queryCoeffCfgAppByPk(CoeffCfgAppVO inCoeffCfgAppVo) {
		logger.info("根据主键查询提额系数调整申请表的请求参数为："
				+ JSONObject.toJSONString(inCoeffCfgAppVo));
		if (Objects.isNull(inCoeffCfgAppVo)) {
			return null;
		}
		try {
			CoeffCfgApp coeffCfgApp = new CoeffCfgApp();
			beanCopy(inCoeffCfgAppVo, coeffCfgApp);
//			coeffCfgApp = coeffCfgAppDao.queryCoeffCfgAppByPk(coeffCfgApp);
			if (Objects.nonNull(coeffCfgApp)) {
				CoeffCfgAppVO outCoeffCfgAppVo = beanCopy(coeffCfgApp,
						new CoeffCfgAppVO());
				return outCoeffCfgAppVo;
			} else {
				logger.info("根据主键查询提额系数调整申请表的记录为空！");
			}
		} catch (Exception e) {
			logger.error("根据主键查询提额系数调整申请表记录发生异常！", e);
		}
		return null;
	}

	@Override
	public CoeffCfgAppVO querySingleCoeffCfgAppByCondition(
			CoeffCfgAppVO inCoeffCfgAppVo) {
		logger.info("根据条件查询单笔提额系数调整申请表的请求参数为："
				+ JSONObject.toJSONString(inCoeffCfgAppVo));
		if (Objects.isNull(inCoeffCfgAppVo)) {
			return null;
		}
		try {
			CoeffCfgApp coeffCfgApp = new CoeffCfgApp();
			beanCopy(inCoeffCfgAppVo, coeffCfgApp);
			coeffCfgApp = coeffCfgAppDao
					.querySingleCoeffCfgAppByCondition(coeffCfgApp);
			if (Objects.nonNull(coeffCfgApp)) {
				CoeffCfgAppVO outCoeffCfgAppVo = beanCopy(coeffCfgApp,new CoeffCfgAppVO());
				return outCoeffCfgAppVo;
			} else {
				logger.info("根据条件查询单笔提额系数调整申请表的记录为空！");
			}
		} catch (Exception e) {
			logger.error("根据条件查询单笔提额系数调整申请表记录发生异常！", e);
		}
		return null;
	}

	@Override
	public List<CoeffCfgAppVO> queryCoeffCfgAppByCondition(
			CoeffCfgAppVO inCoeffCfgAppVo) {
		logger.info("条件查询提额系数调整申请表的请求参数为："
				+ JSONObject.toJSONString(inCoeffCfgAppVo));
		if (Objects.isNull(inCoeffCfgAppVo)) {
			return null;
		}
		try {
			List<CoeffCfgApp> dataList = coeffCfgAppDao
					.queryCoeffCfgAppByCondition(inCoeffCfgAppVo);
			if (Objects.nonNull(dataList)) {
				List<CoeffCfgAppVO> resultList = new ArrayList<CoeffCfgAppVO>();
				resultList = (List<CoeffCfgAppVO>) beansCopy(dataList,CoeffCfgAppVO.class);
				return resultList;
			} else {
				logger.info("条件查询提额系数调整申请表的数据为空！");
			}
		} catch (Exception e) {
			logger.error("条件查询提额系数调整申请表发生异常！", e);
		}
		return null;
	}

	@Override
	public List<CoeffCfgAppVO> queryCoeffCfgAppByConditionByPage(
			CoeffCfgAppVO inCoeffCfgAppVo) {
		logger.info("条件分页查询提额系数调整申请表的请求参数为："
				+ JSONObject.toJSONString(inCoeffCfgAppVo));
		if (Objects.isNull(inCoeffCfgAppVo)) {
			return null;
		}
		try {
			List<CoeffCfgApp> dataList = coeffCfgAppDao
					.queryCoeffCfgAppByConditionByPage(inCoeffCfgAppVo);
			if (Objects.nonNull(dataList)) {
				List<CoeffCfgAppVO> resultList = new ArrayList<CoeffCfgAppVO>();
				resultList = (List<CoeffCfgAppVO>) beansCopy(dataList,CoeffCfgAppVO.class);
				return resultList;
			} else {
				logger.info("条件分页查询提额系数调整申请表的数据为空！");
			}
		} catch (Exception e) {
			logger.error("条件分页查询提额系数调整申请表发生异常！", e);
		}
		return null;
	}
	
	 /**
     * 按法人机构查询是否有审批中的申请记录
     * @param legalOrgCode
     * @return
     */
	@Override
	public List<CoeffCfgAppVO> queryCoeffCfgAppByLegalOrgCode(String legalOrgCode) {
		if ("".equals(legalOrgCode)) {
			return null;
		}
		try {
			List<CoeffCfgApp> dataList = coeffCfgAppDao.queryCoeffCfgAppByLegalOrgCode(legalOrgCode);
			if (Objects.nonNull(dataList)) {
				List<CoeffCfgAppVO> resultList = (List<CoeffCfgAppVO>) beansCopy(dataList,CoeffCfgAppVO.class);
				return resultList;
			}else {
				logger.info("查询提额系数调整申请表的数据为空！");
			}
		} catch (Exception e) {
			logger.error("查询提额系数调整申请表发生异常！", e);
		}
		return null;
	}

	/**
	 * 审批通过
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void pass(String bizSerno, PageApproveVO pageApproveVo) {
		logger.info("额度调整申请通过流水号:" + bizSerno);
		int num = 0;
		
		try {
			if (Objects.nonNull(bizSerno) && !"".equals(bizSerno)) {
				CoeffCfgApp inputApp = new CoeffCfgApp();
				inputApp.setBizSerno(bizSerno);
				
				List<CoeffCfgApp> coeffCfgApps = (List<CoeffCfgApp>) coeffCfgAppDao.queryCoeffCfgAppByPk(inputApp);
				
				if (Objects.nonNull(coeffCfgApps)&& coeffCfgApps.size() > 0) {
				
				for (int i = 0; i < coeffCfgApps.size(); i++) {
					
					String leageOrgCode = coeffCfgApps.get(i).getLegalOrgCode();
					String typeId = coeffCfgApps.get(i).getTypeId();
					
					BigDecimal coefficientT = coeffCfgApps.get(i).getNewCoefficient();
					
					//省级修改更新时
					if ("00001".equals(leageOrgCode)) {
						//设置申请记录需更新的值
						CoeffCfgApp coeffCfgApp = coeffCfgApps.get(i);
						coeffCfgApp.setAprvStatus(ConsoleConstant.APRV_STATUS_03);
						coeffCfgApp.setLastUpdateUser(pageApproveVo.getAprvUserId());
						coeffCfgApp.setLastUpdateTime(pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001));
						// 修改额度申请表
						num += coeffCfgAppDao.updateCoeffCfgAppByPk(coeffCfgApp);

						CoeffCfg coeffCfg = new CoeffCfg();
						coeffCfg.setTypeId(typeId);
						coeffCfg.setLegalOrgCode(leageOrgCode);
//						coeffCfg.setCoefficient(coefficientT);
						
						CoeffCfg out = coeffCfgDao.queryCoeffCfgByPk(coeffCfg);
						
						coeffCfg.setLegalOrgCode(coeffCfgApps.get(i).getLegalOrgCode());
						coeffCfg.setCoefficient(coeffCfgApps.get(i).getNewCoefficient());
						coeffCfg.setChangeNum(out.getChangeNum() + 1);
						coeffCfg.setLastUpdateTime(TimeUtil.getCurrentDateTime());
						

						// 修改额度表的系数、调整次数
						int count = coeffCfgDao.updateCoeffCfgByPk(coeffCfg);

//						CoeffCfg in = new CoeffCfg();
//						in.setTypeId(typeId);
//						in.setCoefficient(coefficientT);
//						
						//按注册单位号查询其他机构中的记录(系数大于省级配置的)
						List<CoeffCfg> list = coeffCfgDao.queryCoeffCfgByTypeId(coeffCfg);
						if (list != null && list.size()>0) {
							
							for (int j = 0; j < list.size(); j++) {
								CoeffCfg updateIn = new CoeffCfg();
								updateIn.setCoefficient(coefficientT);
								updateIn.setTypeId(list.get(j).getTypeId());
								updateIn.setLegalOrgCode(list.get(j).getLegalOrgCode());
								//更新其他机构的系数（大于省级配置则更新为省级配置）
								num = coeffCfgDao.updateCoeffCfgByPk(updateIn);
							}
						}
					}else {
						
					CoeffCfgApp coeffCfgApp = coeffCfgApps.get(i);
					coeffCfgApp.setAprvStatus(ConsoleConstant.APRV_STATUS_03);
					coeffCfgApp.setLastUpdateUser(pageApproveVo.getAprvUserId());
					coeffCfgApp.setLastUpdateTime(pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001));
					// 修改额度申请表
					num += coeffCfgAppDao.updateCoeffCfgAppByPk(coeffCfgApp);

					CoeffCfg coeffCfg = new CoeffCfg();
					coeffCfg.setTypeId(typeId);
					coeffCfg.setLegalOrgCode(leageOrgCode);
					
					CoeffCfg out = coeffCfgDao.queryCoeffCfgByPk(coeffCfg);
					
					coeffCfg.setLegalOrgCode(coeffCfgApps.get(i).getLegalOrgCode());
					coeffCfg.setCoefficient(coeffCfgApps.get(i).getNewCoefficient());
					coeffCfg.setChangeNum(out.getChangeNum() + 1);
					coeffCfg.setLastUpdateUser(coeffCfgApps.get(i).getCreateUser());
					coeffCfg.setLastUpdateTime(TimeUtil.getCurrentDateTime());
					// 修改额度表的系数、调整次数
					int count = coeffCfgDao.updateCoeffCfgByPk(coeffCfg);

				}
				}
				}
			} else {
				throw new Exception("流水号不能为空");
			}

		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
	}

	/**
	 * 审批不通过
	 */
	@Override
	public void refuse(String bizSerno, PageApproveVO pageApproveVo) {
		logger.info("额度调整申请不通过流水号:" + bizSerno);
		int num = 0;
		try {
			if (Objects.nonNull(bizSerno) && !"".equals(bizSerno)) {
				CoeffCfgApp inputApp = new CoeffCfgApp();
				inputApp.setBizSerno(bizSerno);

				List<CoeffCfgApp> coeffCfgApps = (List<CoeffCfgApp>) coeffCfgAppDao.queryCoeffCfgAppByPk(inputApp);

				for (int i = 0; i < coeffCfgApps.size(); i++) {
					CoeffCfgApp coeffCfgApp = coeffCfgApps.get(i);
					coeffCfgApp.setAprvStatus(ConsoleConstant.APRV_STATUS_04);
					coeffCfgApp.setLastUpdateUser(pageApproveVo.getAprvUserId());
					coeffCfgApp.setLastUpdateTime(pubSysInfoService.getOpenday(BaseConstant.SYS_ID_1001));
					// 修改额度申请表
					num += coeffCfgAppDao.updateCoeffCfgAppByPk(coeffCfgApp);
				}
			}else{
				throw new Exception("流水号不能为空");
			}
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
	}

	@Override
	public void repulse(String bizSerno, PageApproveVO pageApproveVo) {

	}

	@Override
	public List<CoeffCfgAppVO> queryCoeffCfgAppByTypeId(
			CoeffCfgAppVO coeffCfgAppVo) {
		logger.info("查询申请记录参数信息为"+coeffCfgAppVo);
		if ("".equals(coeffCfgAppVo)) {
			return null;
		}
		try {
			List<CoeffCfgApp> listout = coeffCfgAppDao.queryCoeffCfgAppByTypeId(coeffCfgAppVo);
			if (Objects.nonNull(listout)) {
				List<CoeffCfgAppVO> resultList = (List<CoeffCfgAppVO>) beansCopy(listout,CoeffCfgAppVO.class);
				return resultList;
			}else {
				logger.info("查询数据为空");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}
	
}